package com.ruoyi.web.work.controller;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.web.common.Result;
import com.ruoyi.web.work.domain.dbo.KeyBasicDO;
import com.ruoyi.web.work.domain.dbo.KeyProcessDO;
import com.ruoyi.web.work.domain.dbo.KeyUserDO;
import com.ruoyi.web.work.domain.dbo.WasteDO;
import com.ruoyi.web.work.domain.dto.ProcessInputDTO;
import com.ruoyi.web.work.service.KeyProcessService;
import com.ruoyi.web.work.service.KeyUserService;
import com.ruoyi.web.work.service.KeyWasteService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.work.domain.KeyBasic;
import com.ruoyi.web.work.service.IKeyBasicService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

import static com.ruoyi.web.common.Results.ok;

/**
 * 流转作业卡Controller
 *
 * @author gsx
 * @date 2021-02-28
 */
@RestController
@RequestMapping("/work/basic")
public class KeyBasicController extends BaseController
{
    @Resource
    private IKeyBasicService keyBasicService;

    @Resource
    private KeyProcessService keyProcessService;

    @Resource
    private KeyUserService keyUserService;

    @Resource
    private KeyWasteService keyWasteService;

    /**
     * 查询流转作业卡列表
     */
    @PreAuthorize("@ss.hasPermi('work:basic:list')")
    @GetMapping("/list")
    public TableDataInfo list(KeyBasic keyBasic)
    {
        startPage();
        List<KeyBasic> list = keyBasicService.selectKeyBasicList(keyBasic);
        return getDataTable(list);
    }

    /**
     * 导出流转作业卡列表
     */
    @PreAuthorize("@ss.hasPermi('work:basic:export')")
    @Log(title = "流转作业卡", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(KeyBasic keyBasic)
    {
        List<KeyBasic> list = keyBasicService.selectKeyBasicList(keyBasic);
        ExcelUtil<KeyBasic> util = new ExcelUtil<KeyBasic>(KeyBasic.class);
        return util.exportExcel(list, "basic");
    }

    /**
     * 获取流转作业卡详细信息
     */
    @PreAuthorize("@ss.hasPermi('work:basic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(keyBasicService.selectKeyBasicById(id));
    }

    /**
     * 新增流转作业卡
     */
    @PreAuthorize("@ss.hasPermi('work:basic:add')")
    @Log(title = "流转作业卡", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KeyBasic keyBasic)
    {
        return toAjax(keyBasicService.insertKeyBasic(keyBasic));
    }

    /**
     * 修改流转作业卡
     */
    @PreAuthorize("@ss.hasPermi('work:basic:edit')")
    @Log(title = "流转作业卡", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KeyBasic keyBasic)
    {
        return toAjax(keyBasicService.updateKeyBasic(keyBasic));
    }

    /**
     * 删除流转作业卡
     */
    @PreAuthorize("@ss.hasPermi('work:basic:remove')")
    @Log(title = "流转作业卡", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(keyBasicService.deleteKeyBasicByIds(ids));
    }

    /**
     * 流转作业卡工序录入
     */
//    @PreAuthorize("@ss.hasPermi('work:basic:remove')")
    @Log(title = "工序录入", businessType = BusinessType.INSERT)
    @PostMapping("/processInput")
    @Transactional(rollbackFor = Exception.class)
    public Result processInput(@RequestBody ProcessInputDTO processInputDTO)
    {
        processInputDTO.getKeyProcessDOList().stream().forEach(keyProcessDTO -> {
            KeyProcessDO keyProcessDO = BeanUtil.toBean(keyProcessDTO, KeyProcessDO.class);
            keyProcessService.save(keyProcessDO);
            keyProcessDTO.getUserIdList().stream().forEach(userId ->{
                KeyUserDO keyUserDO = BeanUtil.toBean(keyProcessDTO, KeyUserDO.class);
                keyUserDO.setProcessId(keyProcessDO.getId());
                keyUserDO.setUserId(userId);
                keyUserDO.setNum(keyProcessDTO.getNum()+keyProcessDTO.getUserIdList().size()/1.0);
                keyUserService.save(keyUserDO);
            });
        });

        return ok();
    }

    /**
     * 流转作业卡工序录入
     */
//    @PreAuthorize("@ss.hasPermi('work:basic:remove')")
    @Log(title = "检验", businessType = BusinessType.INSERT)
    @PostMapping("/checkInput")
    @Transactional(rollbackFor = Exception.class)
    public Result checkInput(@RequestParam(value = "wasteDOList") List<WasteDO> wasteDOList)
    {
        wasteDOList.stream().forEach(wasteDO -> {
            keyWasteService.saveOrUpdate(wasteDO);
        });

        Integer wasteTotal = wasteDOList.stream().map(wasteDO -> wasteDO.getNum()).reduce(Integer::sum).get();

        KeyBasicDO keyBasicDO = keyBasicService.getById(wasteDOList.get(0).getBatch());
        keyBasicDO.setFpy(keyBasicDO.getNum()/(wasteTotal+0.0));
        keyBasicDO.setWasteNum(wasteTotal);
        keyBasicService.updateById(keyBasicDO);
        return ok();
    }
}
